#include "precompiled.h"
#include "connectorthread.h"
#include "sslclient.h"

#include <protocol/message.h>

namespace Opl
{
	namespace Helpers
	{

		class ConnectorThreadPrivate
		{
			public:
				ConnectorThreadPrivate(): stopRequired(false), client(0) {}
				~ConnectorThreadPrivate() {}

				bool stopRequired;
				SslClient* client;
				ConnectorSetup setup;
				void clear() 
				{
				}
		};

		ConnectorThread* ConnectorThread::instance()
		{
			static QSharedPointer<ConnectorThread> thread(new ConnectorThread);
			return thread.data();
		}

		ConnectorThread::ConnectorThread(QObject* parent) :
			QThread(parent), O_PRIVATE_CREATE(ConnectorThread)
		{
			O_D(ConnectorThread);
			//d->
		}

		ConnectorThread::~ConnectorThread()
		{
			O_PRIVATE_DELETE;
		}


		void ConnectorThread::stop()
		{
			O_D(ConnectorThread);
			d->stopRequired = true;
			d->client->stop();
		}

		void ConnectorThread::Setup(const ConnectorSetup& setup)
		{
			O_D(ConnectorThread);
			logger()->info("Connector::Setup");
			d->setup = setup;
		}

		void ConnectorThread::Send(const QString& data)
		{
			O_D(ConnectorThread);
			if (!d->client)
			{
				logger()->error("ConnectorThread::Send. Client not initialized");
				return;
			}

			d->client->Send(data);
		}

		void ConnectorThread::clientConnected()
		{
			O_D(ConnectorThread);
			logger()->info("ConnectorThread::clientConnected()");
			emit connected();
		}

		void ConnectorThread::clientDisconnected()
		{
			O_D(ConnectorThread);
			logger()->info("ConnectorThread::clientConnected()");
			emit disconnected();
		}

		void ConnectorThread::run()
		{
			O_D(ConnectorThread);
			logger()->info("ConnectorThread::run()");

			if (!d->client)
			{
				d->client = new SslClient(d->setup.host, d->setup.port);
				d->client->moveToThread(this);
				connect(d->client, SIGNAL(connected()), this, SLOT(clientConnected()));
				connect(d->client, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
				d->client->start();
			}

			exec();
		}

	}
}